package userlog

import (
	"context"
	"time"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLogListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLogListLogic {
	return &UserLogListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLogListLogic) UserLogList(req *types.UserLogListRo) (resp *types.UserLogListRsp, err error) {
	sess := l.svcCtx.DB.WithContext(l.ctx).Model(&model.UserLog{})

	sess.Select("UserLog.*,User.Username,ActionConfig.Name AS ActionName").
		Joins("LEFT JOIN User ON User.Id=UserLog.Uid").
		Joins("LEFT JOIN ActionConfig ON ActionConfig.Method=UserLog.Method AND ActionConfig.Path=UserLog.URI")

	if req.Begin > 0 {
		sess = sess.Where("UserLog.CreatedAt>=?", time.Unix(req.Begin, 0).Format(time.RFC3339))
	}
	if req.End > 0 {
		sess = sess.Where("UserLog.CreatedAt<?", time.Unix(req.End, 0).Format(time.RFC3339))
	}
	if req.Uid > 0 {
		sess = sess.Where("UserLog.Uid=?", req.Uid)
	}
	if req.Path != "" {
		sess = sess.Where("UserLog.URI=?", req.Path)
	}
	if req.IP != "" {
		sess = sess.Where("UserLog.IP=?", req.IP)
	}

	var total int64
	if err := sess.Count(&total).Error; err != nil {
		return nil, err
	}
	var beans []model.BeanUserLog
	if err := sess.Order("ID DESC").Limit(req.Size).Offset((req.Page - 1) * req.Size).
		Find(&beans).Error; err != nil {
		return nil, err
	}

	resp = new(types.UserLogListRsp)
	resp.Total = total
	for _, v := range beans {
		resp.Items = append(resp.Items, types.UserLog{
			ID:         v.ID,
			CreatedAt:  v.CreatedAt.Format(time.RFC3339),
			Uid:        v.Uid,
			UserName:   v.Username,
			Ip:         v.IP,
			Method:     v.Method,
			Uri:        v.URI,
			ActionName: v.ActionName,
		})
	}
	return
}
